<script lang="ts">
import { defineComponent } from "vue";
import { ElForm, ElFormItem, ElInput, ElButton } from "element-plus";
import md5 from "md5";

export default defineComponent({
  name: "Register",
  components: {
    ElForm,
    ElFormItem,
    ElInput,
    ElButton,
  },
  data() {
    return {
      registerForm: {
        username: "",
        password: "",
      },
      registerRules: {
        username: [
          { required: true, message: "Please enter username", trigger: "blur" },
        ],
        password: [
          { required: true, message: "Please enter password", trigger: "blur" },
        ]
      },
    };
  },
  methods: {
    async register() {
      try {
        console.log(JSON.stringify(this.registerForm));

        // 对密码进行 MD5 加密
        const encryptedPassword = md5(this.registerForm.password);

        // 构造请求体
        const requestBody = {
          username: this.registerForm.username,
          password: encryptedPassword,
        };

        // 发送注册请求
        const response = await fetch("http://localhost:8080/api/user/reg", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(requestBody),
        }).then((res) => res.json());

        // 如果注册成功，跳转到登录页
        if (response.success) {
          alert("Registration successful.");
          localStorage.setItem("token", response.token);
          // 跳转到登录页
          this.$router.push("/index");
        } else {
          // 处理注册失败
          alert("Registration failed");
          // 给用户一个提示
        }
      } catch (e) {
        alert("Registration failed");
        // 给用户一个提示
      }
    },
  },
});
</script>

<template>
  <div class="register-container">
    <el-form
      ref="registerForm"
      :model="registerForm"
      :rules="registerRules"
      class="register-form"
    >
      <el-form-item prop="username">
        <el-input
          v-model="registerForm.username"
          placeholder="Username"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="registerForm.password"
          type="password"
          placeholder="Password"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="register">Register</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.register-form {
  width: 300px;
}
</style>